package com.wosiliujing.learning.util;

import cn.hutool.core.util.ObjectUtil;
import com.wosiliujing.learning.entity.SecurityUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/***
 *
 * @author 刘靖
 * @date 2019/5/6 23:59
 */
@UtilityClass
public class SecurityUtil {

    /**
     * 获取 Authentication
     * @return
     */
    public  Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前登陆用户
     * @author 刘靖
     * @date 2019/12/10 15:09
     * @return  当前登陆的用户信息
     */
    public SecurityUser getUser(){
        Authentication authentication = getAuthentication();
        if(ObjectUtil.isEmpty(authentication)){
            return null;
        }
        Object object = authentication.getPrincipal();
        if (object instanceof SecurityUser) {
            return (SecurityUser)object;
        }
        return null;
    }

    /***
     * 获取当前登陆用户的权限
     * @author 刘靖
     * @date 2020/6/4 17:07
     * @return 权限列表
     */
    public List<String> getPermission(){
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> permissions = authorities.stream()
                .map(authority -> authority.getAuthority()).collect(Collectors.toList());
        return  permissions;
    }
}
